<!--
 * @Descripttion: 课堂分析详情-教师行为-习惯用语
 * @version: V1.0.0.1
 * @Author: zhaozhenzhuo
 * @Date: 2025-10-28 16:16:58
 * @LastEditors: zhaozhenzhuo
 * @LastEditTime: 2025-10-28 16:16:58
-->
<template>
	<div :class="type === 1 ? 'common-slang-wrapper' : 'sensitive-word-wrapper'">
		<div class="module-title-wrapper">
			<p>{{ type === 1 ? '习惯用语' : '敏感词' }}</p>
			<img
				v-if="type === 2 && false"
				src="@/assets/images/lessonAnalysisDetails/text-edit-normal.png"
			/>
		</div>
		<template v-if="type === 1">
			<div class="detail">
				<p>
					本堂课老师高频习惯用语共<span v-if="commonSlangList" class="active"
						>{{ commonSlangList.length }}个</span
					><span v-else class="active">-个</span
					><span v-if="commonSlangList && commonSlangList.length"
						>，分别是<span v-for="(item, index) in commonSlangList" :key="index"
							>{{ item.name }}（<span class="active">{{ item.value }}次</span>）<span
								v-if="index !== commonSlangList.length - 1"
								>、</span
							></span
						></span
					>。
				</p>
			</div>
			<div v-if="commonSlangList && commonSlangList.length" class="common-chart"></div>
		</template>
		<template v-else>
			<div class="detail">
				<p>
					本堂课共分析敏感词<span v-if="sensitiveList" class="active"
						>{{ sensitiveList.length }}个</span
					><span v-else class="active">-个</span
					><span v-if="sensitiveList && sensitiveList.length"
						>，分别是<span v-for="(item, index) in sensitiveList" :key="index"
							>{{ item.name }}（<span class="active">{{ item.value }}次</span>）<span
								v-if="index !== sensitiveList.length - 1"
								>、</span
							></span
						></span
					>。
				</p>
			</div>
			<div v-if="sensitiveList && sensitiveList.length" class="sensitive-chart"></div>
		</template>
	</div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import 'echarts-wordcloud';
import { ref, shallowRef, computed, watch, nextTick, onMounted, onUnmounted } from 'vue';
import type { CourseListItemType, AnalysisResultType, KeyWordType } from './KeywordResult.type';
import { getErrorMessage, getSpecialWordResultAPI } from '@/api/index';

const props = withDefaults(
	defineProps<{
		queryObj: {
			lessonInfo: CourseListItemType | null;
			aiScoreResult: AnalysisResultType | null;
			offsetTime: number;
			videoBeginTime: number;
		} | null;
		type: number;
	}>(),
	{
		queryObj: null,
		type: 1
	}
);

const emit = defineEmits<{
	(e: 'changeVideoTime', time: number): void; // 切换视频时间
	(e: 'searchTextBoard', name: string): void; // 搜索文本板
}>();

const lessonInfo = computed(() => props.queryObj?.lessonInfo);

watch(
	() => props.queryObj,
	(val) => {
		if (val && val.aiScoreResult && val.lessonInfo) {
			nextTick(() => {
				if (props.type === 1) {
					getCommonSlangList();
				} else {
					getSensitiveList();
				}
			});
		}
	},
	{ immediate: true }
);

onMounted(() => {
	window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
	window.removeEventListener('resize', resizeHandler);
	if (chart.value) {
		chart.value.dispose();
	}
});

const resizeHandler = () => {
	setTimeout(() => {
		if (chart.value) {
			chart.value.resize();
		}
	}, 300);
};

// 习惯用语列表
const commonSlangList = ref<KeyWordType[]>([]);
// 查询常用语
const getCommonSlangList = async () => {
	try {
		let data = await getSpecialWordResultAPI({
			lessonCode: lessonInfo.value?.code as string,
			lexiconType: 1000
		});

		// 整理数据
		if (data?.length) {
			// 取次数高于10次的作为高频常用词
			data = data.filter((item) => item.countNum >= 10);
			// 排序
			data.sort((a, b) => {
				return b.countNum - a.countNum;
			});
			// 默认展示前十个
			data = data.splice(0, 10);
			commonSlangList.value = [];
			data.forEach((item) => {
				commonSlangList.value.push({
					name: item.name,
					value: item.countNum
				});
			});
		} else {
			commonSlangList.value = [];
		}
		if (commonSlangList.value && commonSlangList.value.length) {
			nextTick(() => {
				initWordCloudChart(1);
			});
		}
	} catch (err) {
		console.error(getErrorMessage(err));
	}
};

// 敏感词列表
const sensitiveList = ref<KeyWordType[]>([]);
// 查询敏感词
const getSensitiveList = async () => {
	try {
		let data = await getSpecialWordResultAPI({
			lessonCode: lessonInfo.value?.code as string,
			lexiconType: 1001
		});

		// 整理数据
		if (data?.length) {
			// 排序
			data.sort((a, b) => {
				return b.countNum - a.countNum;
			});
			sensitiveList.value = [];
			data.forEach((item) => {
				sensitiveList.value.push({
					name: item.name,
					value: item.countNum
				});
			});
		} else {
			sensitiveList.value = [];
		}
		if (sensitiveList.value && sensitiveList.value.length) {
			nextTick(() => {
				initWordCloudChart(2);
			});
		}
	} catch (err) {
		console.error(getErrorMessage(err));
	}
};

// echarts对象
const chart = shallowRef<echarts.ECharts | null>(null);
// 初始化词云
const initWordCloudChart = (type: number) => {
	// 绘制图像
	if (chart.value) {
		chart.value.dispose();
	}
	if (type === 1) {
		// 习惯用语
		chart.value = echarts.init(document.querySelector('.common-chart') as HTMLElement);
	} else {
		// 敏感词
		chart.value = echarts.init(document.querySelector('.sensitive-chart') as HTMLElement);
	}
	// 定义词云图的配置项
	const option = {
		series: [
			{
				type: 'wordCloud',
				shape: 'circle',
				left: 'center',
				top: 'center',
				right: null,
				bottom: null,
				width: '90%',
				height: '90%',
				gridSize: 10,
				sizeRange: [18, 28],
				rotationRange: [0, 0],
				textStyle: {
					fontFamily: 'Alibaba PuHuiTi',
					fontWeight: 'bold',
					color() {
						const _colorArr = [
							Math.round(Math.random() * 100 + 120),
							Math.round(Math.random() * 100 + 120),
							Math.round(Math.random() * 50 + 180)
						];
						return `rgb(${_colorArr.join(',')})`;
					}
				},
				data: type === 1 ? commonSlangList.value : sensitiveList.value
			}
		]
	};

	// 将配置项设置到 echarts 实例中
	chart.value.setOption(option);
	// 知识点添加点击事件
	chart.value.on('click', (params) => {
		const _list = type === 1 ? commonSlangList.value : sensitiveList.value;
		const _item = _list.find((item) => item.name === params.name);
		if (_item) {
			emit('searchTextBoard', _item.name);
		}
	});
};
</script>

<style lang="scss" scoped>
.common-slang-wrapper,
.sensitive-word-wrapper {
	margin-top: 1.6rem;

	.common-chart,
	.sensitive-chart {
		width: 100%;
		height: 10rem;
		background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);
	}
}
</style>
